<!--客户管理 CustomerManagement-->
<template>
  <div class='page_format'>
    <div class="my_Select">
      <el-form :inline="true" class="search-form">
        <el-form-item>
          <el-button class="bt-color-tjd" type="primary" v-if="is_show_button('button_crs_save')" @click="saveDataForm">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-cascader v-model="projectManager"
                       placeholder="项目经理" multiple clearable
                       :options="userData"
                       :props="{ multiple: false, emitPath: false }"
                       :show-all-levels="false"
                       filterable
                       style="width: 110px;"
                       @change="handleQuery"
          ></el-cascader>
        </el-form-item>
          <el-form-item>
            <el-input style="width:150px;margin-right:8px" size="small" placeholder="公司名称/联系人"
                      v-model.number="queryValue"
                      clearable></el-input>
          </el-form-item>
          <el-button size="small" @click="handleQuery" icon="el-icon-search" type="primary">查询</el-button>
      </el-form>
    </div>
    <el-table :data="list" border style="width: 100%">
      <el-table-column type="index" :index="sort" label="序号" width="50"></el-table-column>
      <el-table-column prop="companyId" label="公司名称" >
        <template v-slot="scope">
          <span>{{ getCompanyText(scope.row.companyId) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="登录账号"></el-table-column>
      <el-table-column prop="companyEmail" label="企业邮箱" ></el-table-column>
      <el-table-column prop="nickName" label="联系人"></el-table-column>
      <el-table-column prop="kind" label="经营品类">
        <template v-slot="scope">
          <span>{{ getDeviceKindText(scope.row.kind) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="companyPhone" label="联系方式"></el-table-column>
      <el-table-column prop="projectManager" label="项目经理">
        <template v-slot="scope">
          <span>{{ getUserNameText(scope.row.projectManager) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="demandCount" label="关联需求">
        <template v-slot="scope">
          <div @click="handleJump(scope.row)" style="color: #409eff;cursor: pointer;">{{ scope.row.demandCount }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="updateTime" label="最新操作时间"></el-table-column>
      <el-table-column v-if="is_show_button('button_crs_save')" fixed="right" label="操作" width="100" align="center">
        <template v-slot="scope">
          <div>
            <el-button @click="handleJump(scope.row)" type="text" size="small">
              查看需求
            </el-button>
          </div>
<!--          <div>-->
<!--            <el-button @click="handleSetPermissions(scope.row)" type="text" size="small">-->
<!--              设置权限-->
<!--            </el-button>-->
<!--          </div>-->
          <div>
            <el-button @click="handleClick(scope.row)" type="text" size="small">
              编辑
            </el-button>
            <el-button @click="changeStatus(scope.row)" type="text" size="small">
              {{ scope.row.status === "0" ? "禁用" : "启用" }}
            </el-button>
          </div>
          <div>
            <el-button @click="resetPassword(scope.row)" type="text" size="small">
              重置密码
            </el-button>
          </div>
          <el-button @click="handleButtonClick(scope.row)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="form.userId ?'修改':'添加'" :visible.sync="dialogFormVisible" center width="500px"
               @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-form-item label="公司名称：" :label-width="formLabelWidth" prop="companyId">
          <el-select v-model="form.companyId" placeholder="请选择公司名称" style="width: 90%;" @change="handleCompanyChange"
                     :disabled="!!form.userId">
            <el-option
              v-for="item in companyData"
              :key="item.id"
              :label="`${item.companyName}`"
              :value="item.companyId"
            ></el-option>
          </el-select>
          <!-- 感叹号和提示 -->
          <el-tooltip content="请确认是否在设备后台录入" placement="top">
            <i class="el-icon-warning-outline" style="color: #f56c6c; margin-left: 8px; cursor: pointer;"></i>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="登录账号：" :label-width="formLabelWidth" prop="userName">
          <el-input v-model="form.userName" autocomplete="off" placeholder="请填写登录账号" style="width: 90%;"
                    :disabled="!!form.userId"></el-input>
        </el-form-item>
        <el-form-item v-if="!form.userId" label="登录密码：" :label-width="formLabelWidth" prop="password">
          <el-input v-model="form.password" autocomplete="off" placeholder="请填写登录密码" style="width: 90%;"></el-input>
        </el-form-item>
<!--        <el-form-item v-show="form.userId" label="登录密码：" :label-width="formLabelWidth">-->
<!--          <el-input v-model="form.password" autocomplete="off" placeholder="请填写要修改的登录密码" style="width: 90%;"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="经营品类：" :label-width="formLabelWidth" prop="kindList">
          <el-select v-model="form.kindList" placeholder="请选择经营品类" style="width: 90%;" multiple clearable>
            <el-option
              v-for="item in deviceKindData"
              :key="item.id"
              :label="`${item.label}`"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目经理：" :label-width="formLabelWidth" prop="companyId">
          <el-cascader v-model="form.projectManager"
                       placeholder="请选择项目经理" multiple
                       :options="userData"
                       :props="{ multiple: false, emitPath: false }"
                       :show-all-levels="false"
                       filterable
                       style="width: 90%;"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="企业状态：" :label-width="formLabelWidth" prop="status">
          <el-switch
            v-model="form.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="0"
            inactive-value="1"
          ></el-switch>
        </el-form-item>
        <el-form-item label="备注：" :label-width="formLabelWidth">
          <el-input v-model="form.remark" placeholder="请输入介绍信息" autocomplete="off" type="textarea"></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" :disabled="submitLoading">取 消</el-button>
        <el-button class="bt-color-tjd" v-if="is_show_button('button_crs_save')" type="primary"
                   @click="saveDataApi" :loading="submitLoading">确 定
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="设置权限" :visible.sync="setPermissionsShow" center width="900px"
               @close="closeDialog">
      <div>
        <el-divider :style="{ 'font-size': '16px', 'margin-top': '20px', 'margin-bottom': '20px' }"
                    content-position="left" >客户信息</el-divider>
        <el-form :model="form" :label-width="formLabelWidth" size="mini" class="detail">
          <el-form-item label="公司名称：" :label-width="formLabelWidth" style="display: inline-block; width: 40%;">
            <span>{{ getCompanyText(form.companyId) }}</span>
          </el-form-item>
        </el-form>
      </div>
      <el-divider :style="{ 'font-size': '16px', 'margin-top': '20px', 'margin-bottom': '20px' }"
                  content-position="left" >权限设置</el-divider>
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-tree
          ref="menuTree"
          :data="menuTreeData"
          show-checkbox
          node-key="menuId"
          :props="defaultProps"
          @check-change="handleCheckChange"
        >
        </el-tree>
      </el-form>

      <!-- 底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog" :disabled="submitLoading">取 消</el-button>
        <el-button @click="resetSelection">重置</el-button>
        <el-button class="bt-color-tjd" v-if="is_show_button('button_crs_save')" type="primary"
                   @click="saveSetPermissionsDataApi" :loading="submitLoading">确 定
        </el-button>
      </div>
    </el-dialog>

    <Toast :dialogVisible="dialogVisible" @isDelete="deleteDataApi"></Toast>
  </div>
</template>

<script>
import { post } from '@/api/my_axios'
import { changSort } from '@/utils/aqi'

export default {
  name: '',
  data () {
    return {
      setPermissionsShow: false, // 权限按钮loading
      submitLoading: false, // 按钮loading
      dialogFormVisible: false,
      dialogVisible: false,
      dialogShowS: false,
      form: {
        userId: '',
        userName: '',
        roleId: '',
        companyId: '',
        password: '',
        kind: '',
        status: '0',
        remark: '',
        nickName: '',
        userType: '02',
        email: '',
        phoneNumber: '',
        sex: '0',
        menuIdList: [],
        kindList: [],
        projectManager: ''
      },
      list: [],
      companyData: [],
      deviceKindData: [],
      userData: [],
      menuData: [],
      infoForm: {},
      checkedMenuIds: [], // 已勾选的菜单ID
      menuTreeData: [], // 菜单树数据
      defaultProps: { // 默认属性配置
        children: 'children', // 子节点字段
        label: 'menuName', // 显示名称字段
        key: 'menuId' // 唯一标识字段
      },
      projectManager: this.$store.state.module1.UserInfo.roleId === 4 ? this.$store.state.module1.UserInfo.userName : '',
      formLabelWidth: '140px',
      pageSize: 20,
      pageNum: 1,
      total: 0,
      id: '',
      queryValue: '',
      kind: '',
      rules: {
        companyId: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        userName: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        kindList: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        status: [{ required: true, message: '必填项不能为空！', trigger: 'change' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 32, message: '密码必须是6到32个字符之间的字母+数字+符号', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9!@#$%^&*()\-+]+$/,
            message: '密码仅支持数字、字母和特殊符号 (!@#$%^&*()-+)',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (!/[A-Za-z]/.test(value)) {
                callback(new Error('密码必须包含字母'))
              } else if (!/[0-9]/.test(value)) {
                callback(new Error('密码必须包含数字'))
              } else if (!/[!@#$%^&*()\-+]/.test(value)) {
                callback(new Error('密码必须包含特殊符号 (!@#$%^&*()-+)'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },

  mounted () {
    this.getRoleCascadeRelation()
    this.getCompanyList()
    this.getDictSortData()
    this.getCustomerManagement()
    this.getAllMenuList()
  },

  methods: {
    // 排序 （序号）
    sort (index) {
      return changSort(index, this.pageNum, this.pageSize)
    },

    // 公司登录账号
    handleCompanyChange (value) {
      // 查找选中的公司名称对应的 companyId
      const selectedCompany = this.companyData.find(company => company.companyId === value)
      if (selectedCompany) {
        // 自动填充 userName，但用户仍可以手动修改这个值
        this.form.userName = selectedCompany.companyEmail
        this.form.projectManager = selectedCompany.projectManager
      } else {
        // 如果未找到匹配项，清空 userName（可选）
        this.form.userName = ''
        this.form.projectManager = ''
      }
    },

    // 项目经理的转化
    getUserNameText (value) {
      // 遍历 userData，查找匹配的 userName，并返回对应的 nickName
      for (const manager of this.userData) {
        const user = manager.children.find(child => child.value === value)
        if (user) {
          return user.label // 返回对应的 nickName
        }
      }
      return '' // 如果未找到，返回空字符串
    },

    // 公司名的转化
    getCompanyText (value) {
      const dto = this.companyData.find(v => v.companyId === value)
      return dto && dto ? dto.companyName : ''
    },

    // 项目品类的转化
    getDeviceKindText (value) {
      if (!value) return ''
      // 将逗号分隔的字符串拆分为数组
      const valueArray = value.split(',')
      // 遍历数组，通过 `deviceKindData` 查找对应的 label
      const labels = valueArray.map(code => {
        const selectedItem = this.deviceKindData.find(item => item.value === code)
        return selectedItem ? selectedItem.label : code // 如果未找到对应项，返回原始 code
      })
      // 将所有找到的 label 重新拼接成字符串
      return labels.join(', ')
    },

    // 新增
    saveDataForm () {
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.dialogFormVisible = true
      this.form.status = '0'
      this.form.roleId = 2
      this.form.menuIdList = []
      this.form.kindList = ['1']
      this.form.password = 'Csr!123456'
    },

    // 修改
    async handleClick (data) {
      await this.getUserInfo(data.userId)
      this.dialogFormVisible = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
      if (this.form.kind) {
        this.form.kindList = this.form.kind.split(',')
      }
      this.form.menuIdList = this.infoForm.menuIdList
    },

    // 关闭dialog框
    closeDialog () {
      this.setPermissionsShow = false // 权限按钮loading
      this.dialogFormVisible = false
      this.submitLoading = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
      this.form.password = ''
      this.$refs.dialogForm.resetFields()
      this.form.menuIdList = []
    },

    getCustomerManagement () {
      this.list = []
      this.$store.dispatch('getCustomerManagement', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        queryValue: this.queryValue,
        projectManager: this.projectManager
      }).then(res => {
        this.list = res.data
        this.total = res.total
      })
    },

    saveDataApi () {
      this.$refs.dialogForm.validate(valid => {
        if (!valid) return false
        this.submitLoading = true
        this.form.menuIdList = this.checkedMenuIds
        // const dto = this.companyData.find(company => company.companyId === this.form.companyId)
        // if (dto) {
        //   this.form.nickName = dto.companyName
        //   this.form.email = dto.companyEmail
        //   this.form.phoneNumber = dto.companyPhone
        //   if (this.form.projectManager) {
        //     post('/api/crm/sys/manage/management/company/edit', {
        //       companyId: this.form.companyId,
        //       projectManager: this.form.projectManager
        //     })
        //   }
        // }
        this.form.userType = '02'
        this.form.sex = '1'
        this.form.kind = (this.form.kindList && this.form.kindList.length > 0) ? this.form.kindList.join(',') : ''
        if (!this.form.userId) {
          post('/api/crm/sys/manage/crm/user/addUser', this.form).then(req => {
            if (req && req.code === 200) {
              this.$message({ message: req.msg, type: 'success' })
              this.closeDialog()
              this.getCustomerManagement()
            } else {
              this.$message({ message: req.msg, type: 'error' })
            }
          }).finally(() => {
            this.submitLoading = false
          })
        } else {
          post('/api/crm/sys/manage/crm/user/editUser', this.form).then(req => {
            if (req && req.code === 200) {
              this.$message({ message: req.msg, type: 'success' })
              this.closeDialog()
              this.getCustomerManagement()
            } else {
              this.$message({ message: req.msg, type: 'error' })
            }
          }).finally(() => {
            this.submitLoading = false
          })
        }
      })
    },

    deleteDataApi (type) {
      if (type === 'ok') {
        const ids = Array.isArray(this.id) ? '0' : [this.id]
        post('/api/crm/sys/manage/crm/user/removeUser', ids
        ).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: req.msg, type: 'success' })
            this.getCustomerManagement()
          } else {
            this.$message({ message: req.msg, type: 'error' })
          }
        })
      }
      this.dialogVisible = false
    },

    changeStatus (row) {
      const params = {
        userId: '',
        status: ''
      }
      params.userId = row.userId
      params.status = row.status === '0' ? '1' : '0'
      this.$confirm('是否启用/禁用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        post('/api/crm/sys/manage/crm/user/changeUserStatus', params).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: '成功', type: 'success' })
          } else {
            this.$message({ message: '失败', type: 'error' })
          }
        }).finally(() => {
          this.getCustomerManagement()
        })
      })
    },

    resetPassword (row) {
      const params = {
        userId: row.userId,
        password: 'Csr!123456'
      }
      this.$confirm('是否重置密码为：Csr!123456', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        post('/api/crm/sys/manage/crm/user/resetUserPwd', params).then(req => {
          if (req && req.code === 200) {
            this.$message({ message: '成功', type: 'success' })
          } else {
            this.$message({ message: '失败', type: 'error' })
          }
        }).finally(() => {
          this.getCustomerManagement()
        })
      })
    },

    // 保存权限操作
    async saveSetPermissionsDataApi () {
      this.submitLoading = true
      this.form.menuIdList = this.checkedMenuIds
      this.form.roleId = 2
      post('/api/crm/sys/manage/crm/user/editUser', this.form).then(req => {
        if (req && req.code === 200) {
          this.$message({ message: req.msg, type: 'success' })
        } else {
          this.$message({ message: req.msg, type: 'error' })
        }
      }).finally(() => {
        this.closeDialog()
        this.getUserManagement()
      })
    },

    // 设置权限
    async handleSetPermissions (data) {
      // 等待数据获取完成
      await this.getUserInfo(data.userId)
      this.setPermissionsShow = true
      Object.keys(data).forEach(key => {
        this.form[key] = data[key]
      })
      this.checkedMenuIds = this.infoForm.menuIdList
      this.menuTreeData = this.formatToTree(this.menuData)
      // 延迟设置默认勾选，确保 `menuTreeData` 已渲染
      this.$nextTick(() => {
        if (this.$refs.menuTree) {
          this.$refs.menuTree.setCheckedKeys(this.checkedMenuIds) // 默认勾选节点
        }
      })
    },

    // 格式化数据为树形结构
    formatToTree (data) {
      const map = {}
      const result = []
      data.forEach((item) => (map[item.menuId] = { ...item, children: [] }))
      data.forEach((item) => {
        if (item.parentId !== '-1') {
          // map[item.parentId]?.children.push(map[item.menuId])
          if (map[item.parentId] && map[item.parentId].children) {
            map[item.parentId].children.push(map[item.menuId])
          }
        } else {
          result.push(map[item.menuId])
        }
      })
      return result
    },

    // 勾选变化事件处理
    handleCheckChange (node, isChecked, childrenChecked) {
      this.checkedMenuIds = this.$refs.menuTree.getCheckedKeys()
    },

    // 重置勾选
    resetSelection () {
      this.$refs.menuTree.setCheckedKeys([])
      this.checkedMenuIds = []
    },

    async getUserInfo (userId) {
      this.infoForm = {}
      const res = await this.$store.dispatch('getUserInfo', userId)
      this.infoForm = res.data
    },

    // 根据全部菜单信息
    getAllMenuList (value) {
      this.$store.dispatch('getAllMenuList', value).then(res => {
        this.menuData = res.data
      })
    },

    // 公司列表
    getCompanyList (value) {
      this.$store.dispatch('getCompanyList', value).then(res => {
        this.companyData = res.data
      })
    },

    // 数据字典配置分类项获取
    getDictSortData () {
      // 项目品类
      this.$store.dispatch('getSysDictItemList', 'deviceKind').then(res => {
        this.deviceKindData = res
      })
    },

    // 用户级联关系
    getRoleCascadeRelation () {
      this.$store.dispatch('getRoleCascadeRelation').then(res => {
        const array = []
        res.forEach(item => {
          if (item.userInfoVOList && item.userInfoVOList.length) {
            array.push({
              value: item.firstLevelId,
              label: item.firstLevelName,
              children: item.userInfoVOList.map(item1 => {
                // 建立 userName 和公司名之间的映射关系
                return {
                  value: item1.userName,
                  label: item1.nickName
                }
              })
            })
          }
        })
        this.userData = array
      })
    },

    handleQuery () {
      this.pageNum = 1
      this.getCustomerManagement()
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.getCustomerManagement()
    },

    handleCurrentChange (val) {
      this.pageNum = val
      this.getCustomerManagement()
    },

    handleButtonClick (data) {
      this.id = data.userId
      this.dialogVisible = true
    },

    handleJump (row) {
      // 需要传的数据
      this.$router.replace({
        path: '/Customer/DemandCustomer',
        query: { userName: row.userName, name: '需求列表' }
      })
    },

    is_show_button (name) {
      let show = false
      this.$store.state.module1.menu_list.forEach(v => {
        // eslint-disable-next-line eqeqeq
        if (v.path === name) {
          show = true
        }
      })
      return show
    }
  }
}
</script>

<style lang='scss'>
  .page_format {
    padding: 56px 20px 140px 20px;
  }
  .search-form{
    margin-top: 10px;
  }

  .icon-image {
    width: auto;
    height: auto;
    object-fit: cover;
  }
</style>
